const menu = require('./menu')

module.exports = async (app) => {
  const mongoose = app.mongoose
  const { Schema } = mongoose

  const SystemSchema = new Schema(
    {},
    {
      timestamps: true,
    }
  )

  const System = mongoose.model('System', SystemSchema, 'system')

  const system = await System.findOne()

  if (!system) {
    System.create({})

    const { User, Admin, AdminRole, Config, AdminMenu } = app.model

    // 创建角色
    const superAdmin = await AdminRole.findOneAndUpdate(
      {
        roleName: '超级管理员',
      },
      {
        roleName: '超级管理员',
        isOpen: true,
        isAdmin: true,
        systemType: 'admin',
      },
      {
        upsert: true,
        overwrite: true,
        new: true,
      }
    )

    // 创建用户（管理员）
    ;[
      {
        username: 'llz',
        password: 'f3abb86bd34cf4d52698f14c0da1dc60',
        systemType: 'admin',
        isOpen: true,
        isAdmin: true,
        roleId: superAdmin._id,
      },
    ].map(async (item) => {
      await Admin.findOneAndUpdate(
        {
          username: item.username,
        },
        item,
        {
          upsert: true,
          setDefaultsOnInsert: true,
        }
      )
    })

    // 创建配置
    await Config.findOneAndUpdate(
      {
        configType: 'system',
      },
      {
        configName: '系统配置',
        configType: 'system',
        config: {
          title: '疫情防控',
        },
        isOpen: true,
      },
      {
        upsert: true, // 不存在插入
        setDefaultsOnInsert: true, // 允许插入默认值
      }
    )

    menu(app)
  }
}
